package com.aya.base.job.ext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.*;
import org.quartz.impl.JobDetailImpl;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.MethodInvoker;

import java.lang.reflect.Method;
import java.util.Map;

public class AyaJobDetailFactoryBean
        implements FactoryBean<JobDetail>, BeanNameAware, ApplicationContextAware, InitializingBean {


    @Nullable
    private String name;

    @Nullable
    private String group;
    @Nullable
    private String targetObject;
    @Nullable
    private String targetMethod;

    private JobDataMap jobDataMap = new JobDataMap();

    private boolean durability = false;

    private boolean requestsRecovery = false;

    @Nullable
    private String description;

    @Nullable
    private String beanName;

    @Nullable
    private ApplicationContext applicationContext;

    @Nullable
    private String applicationContextJobDataKey;

    @Nullable
    private JobDetail jobDetail;


    /**
     * Specify the job's name.
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * Specify the job's group.
     */
    public void setGroup(String group) {
        this.group = group;
    }

    /**
     * Set the job's JobDataMap.
     *
     * @see #setJobDataAsMap
     */
    public void setJobDataMap(JobDataMap jobDataMap) {
        this.jobDataMap = jobDataMap;
    }

    /**
     * Return the job's JobDataMap.
     */
    public JobDataMap getJobDataMap() {
        return this.jobDataMap;
    }

    @Nullable
    public String getTargetObject() {
        return this.targetObject;
    }

    public void setTargetObject(@Nullable String targetObject) {
        this.targetObject = targetObject;
    }

    @Nullable
    public String getTargetMethod() {
        return this.targetMethod;
    }

    public void setTargetMethod(@Nullable String targetMethod) {
        this.targetMethod = targetMethod;
    }

    /**
     * Register objects in the JobDataMap via a given Map.
     * <p>These objects will be available to this Job only,
     * in contrast to objects in the SchedulerContext.
     * <p>Note: When using persistent Jobs whose JobDetail will be kept in the
     * database, do not put Spring-managed beans or an ApplicationContext
     * reference into the JobDataMap but rather into the SchedulerContext.
     *
     * @param jobDataAsMap Map with String keys and any objects as values
     *                     (for example Spring-managed beans)
     * @see org.springframework.scheduling.quartz.SchedulerFactoryBean#setSchedulerContextAsMap
     */
    public void setJobDataAsMap(Map<String, ?> jobDataAsMap) {
        getJobDataMap().putAll(jobDataAsMap);
    }

    /**
     * Specify the job's durability, i.e. whether it should remain stored
     * in the job store even if no triggers point to it anymore.
     */
    public void setDurability(boolean durability) {
        this.durability = durability;
    }

    /**
     * Set the recovery flag for this job, i.e. whether or not the job should
     * get re-executed if a 'recovery' or 'fail-over' situation is encountered.
     */
    public void setRequestsRecovery(boolean requestsRecovery) {
        this.requestsRecovery = requestsRecovery;
    }

    /**
     * Set a textual description for this job.
     */
    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public void setBeanName(String beanName) {
        this.beanName = beanName;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    /**
     * Set the key of an ApplicationContext reference to expose in the JobDataMap,
     * for example "applicationContext". Default is none.
     * Only applicable when running in a Spring ApplicationContext.
     * <p>In case of a QuartzJobBean, the reference will be applied to the Job
     * instance as bean property. An "applicationContext" attribute will correspond
     * to a "setApplicationContext" method in that scenario.
     * <p>Note that BeanFactory callback interfaces like ApplicationContextAware
     * are not automatically applied to Quartz Job instances, because Quartz
     * itself is responsible for the lifecycle of its Jobs.
     * <p><b>Note: When using persistent job stores where JobDetail contents will
     * be kept in the database, do not put an ApplicationContext reference into
     * the JobDataMap but rather into the SchedulerContext.</b>
     *
     * @see org.springframework.scheduling.quartz.SchedulerFactoryBean#setApplicationContextSchedulerContextKey
     * @see org.springframework.context.ApplicationContext
     */
    public void setApplicationContextJobDataKey(String applicationContextJobDataKey) {
        this.applicationContextJobDataKey = applicationContextJobDataKey;
    }


    @Override
    public void afterPropertiesSet() {
        Assert.notNull(this.targetObject, "Property 'targetObject' is required");
        Assert.notNull(this.targetMethod, "Property 'targetMethod' is required");

        if (this.name == null) {
            this.name = this.beanName;
        }
        if (this.group == null) {
            this.group = Scheduler.DEFAULT_GROUP;
        }
        if (this.applicationContextJobDataKey != null) {
            if (this.applicationContext == null) {
                throw new IllegalStateException(
                        "JobDetailBean needs to be set up in an ApplicationContext " +
                                "to be able to handle an 'applicationContextJobDataKey'");
            }
            getJobDataMap().put(this.applicationContextJobDataKey, this.applicationContext);
        }

        JobDetailImpl jdi = new JobDetailImpl();
        jdi.setName(this.name != null ? this.name : toString());
        jdi.setGroup(this.group);
        jdi.setJobClass(BeanJobClass.class);
        jdi.setJobDataMap(this.jobDataMap);
        jdi.setDurability(this.durability);
        jdi.setRequestsRecovery(this.requestsRecovery);
        jdi.setDescription(this.description);
        this.jobDetail = jdi;
    }


    @Override
    @Nullable
    public JobDetail getObject() {
        return this.jobDetail;
    }

    @Override
    public Class<?> getObjectType() {
        return JobDetail.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }



    public class BeanJobClass implements Job{
        private final String targetObject;
        private final String targetMethod;

        public BeanJobClass(String targetObject, String targetMethod) {
            this.targetObject = targetObject;
            this.targetMethod = targetMethod;
        }
        protected Log logger = LogFactory.getLog(getClass());

        /**
         * When invoked by a Quartz scheduler, <code>execute</code> invokes a method on a bean deployed within the scheduler's Spring ApplicationContext.
         * <p>
         * <b>Implementation</b><br>
         * The bean is identified by the "targetBean" entry in the JobDataMap of the JobExecutionContext provided.<br>
         * The method is identified by the "targetMethod" entry in the JobDataMap of the JobExecutionContext provided.<br>
         * <p>
         * The Quartz scheduler shouldn't start up correctly if the bean identified by "targetBean" cannot be found in the scheduler's Spring ApplicationContext.  BeanFactory.getBean()
         * throws an exception if the targetBean doesn't exist, so I'm not going to waste any code testing for the bean's existance in the ApplicationContext.
         * <p>
         * Logging is provided at the DEBUG and INFO levels; 5 lines at the DEBUG level, and 1 line at the INFO level.
         * @see Job#execute(JobExecutionContext)
         */
        @Override
        public void execute(JobExecutionContext context) throws JobExecutionException
        {
            try
            {
                logger.debug("start");

                String targetBean = context.getMergedJobDataMap().getString("targetBean");
                logger.debug("targetBean is "+targetBean);
                if(targetBean==null)
                    throw new JobExecutionException("targetBean cannot be null.", false);

                String targetMethod = context.getMergedJobDataMap().getString("targetMethod");
                logger.debug("targetMethod is "+targetMethod);
                if(targetMethod==null)
                    throw new JobExecutionException("targetMethod cannot be null.", false);

                // when org.quartz.jobStore.useProperties=="true" the arguments entry (which should be an Object[]) in the JobDataMap gets converted into a String.
                Object argumentsObject = context.getMergedJobDataMap().get("arguments");
                Object[] arguments = (argumentsObject instanceof String) ? null : (Object[])argumentsObject;
                logger.debug("arguments array is "+arguments);

                Object bean = applicationContext.getBean(targetBean);
                logger.debug("applicationContext resolved bean name/id '"+targetBean+"' to "+bean);

                MethodInvoker beanMethod = new MethodInvoker();
                beanMethod.setTargetObject(bean);
                beanMethod.setTargetMethod(targetMethod);
                beanMethod.setArguments(arguments);
                beanMethod.prepare();
                logger.info("Invoking Bean: "+targetBean+"; Method: "+targetMethod+"; arguments: "+arguments+";");
                beanMethod.invoke();
            }
            catch(JobExecutionException e)
            {
                throw e;
            }
            catch(Exception e)
            {
                throw new JobExecutionException(e);
            }
            finally
            {
                logger.debug("end");
            }
        }
    }

}
